<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>班级管理</title>
    <link rel="stylesheet" href="${ctxPath}/assets/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="${ctxPath}/assets/module/admin.css"/>
</head>

<body>
<% include("../layout/loading.html"){} %>

<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form toolbar">
                <form id="form">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <div class="layui-form-item">
                                <label class="layui-form-label w-auto">班级名称:</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="className"  autocomplete="off" placeholder="请输入班级名称" class="layui-input">
                                </div>
                            </div>
                        </div>
<!--                        <div class="layui-inline">-->
<!--                            <select name="schoolId">-->
<!--                                <option value="">全部校区</option>-->
<!--                                <% for(school in schoolList) { %>-->
<!--                                <option value="${school.id}">${school.schoolName}</option>-->
<!--                                <% } %>-->
<!--                            </select>-->
<!--                        </div>-->
<!--                        <div class="layui-inline">-->
<!--                            <select name="toOrganizationId">-->
<!--                                <option value="">全部机构</option>-->
<!--                                <% for(organization in organizationList) { %>-->
<!--                                <option value="${organization.id}">${organization.organizationName}</option>-->
<!--                                <% } %>-->
<!--                            </select>-->
<!--                        </div>-->
                        <div class="layui-inline">
                            <div class="layui-form-item">
                                <label class="layui-form-label w-auto">所属机构:</label>
                                <div class="layui-input-inline">
                                    <select name="toOrganizationId" id="toOrganizationId"  lay-verType="tips"
                                            lay-filter="organization">
                                        <option value="">全部</option>
                                        <% for(organizations in organizationList) { %>
                                        <option value="${organizations.id}">${organizations.organizationName}</option>
                                        <% } %>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <div class="layui-form-item">
                                <label class="layui-form-label w-auto">所属校区:</label>
                                <div class="layui-input-inline">
                                    <select name="schoolId" id="toschoolId" lay-verType="tips" lay-filter="school">
                                        <option value="">全部</option>
                                        <% for(school in schoolList) { %>
                                        <option value="${school.id}">${school.schoolName}</option>
                                        <% } %>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button lay-filter="btnSearch" lay-submit type="submit" class="layui-btn icon-btn"><i class="layui-icon layui-icon-search"></i>搜索</button>
                            <button lay-filter="btnReset" lay-submit type="submit" class="layui-btn icon-btn layui-btn-warn"><i class="layui-icon layui-icon-refresh-3"></i>重置</button>
                            <button data-button="class:add"  lay-filter="btnAdd" lay-submit type="submit" class="layui-btn icon-btn layui-btn-normal role_menu"><i class="layui-icon layui-icon-add-1"></i>新增</button>
                        </div>
                    </div>
                </form>
            </div>
            <table class="layui-table" id="TABLE" lay-filter="TABLE"></table>
        </div>
    </div>

</div>

<!-- js部分 -->
<script type="text/javascript" src="${ctxPath}/assets/libs/layui/layui.js"></script>
<script type="text/javascript" src="${ctxPath}/assets/js/common.js"></script>
<script>
    var [maxRole,maxRoleSerialNumber,schoolList,courseList,sysUserList,teacherList] = ["${maxRole}",eval('${maxRoleSerialNumber}'),eval('${schoolList}'),eval('${courseList}'),eval('${sysUserList}'),eval('${teacherList}')];
    layui.use(["layer", "form", "table", "util" ], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;

        var cols = [
                {type: "numbers",width:50},
                {title:"班级名称",field:"className" },
                {title:"所属校区",field:"schoolName" },
                {title:"所属机构",field:"toOrganizationName" },
                {title:"班级负责人",field:"sysUserName" },
                {title:"分配教师",field:"teacherName" },
                {title:"分配课程",field:"distributionCourse", templet:d=>   !d.distributionCourse
                        ? "" 
                        : courseList.filter(i=>d.distributionCourse.split(",").includes(String(i.id))).map(i=>i.courseName).join(",")},
                {title: '操作', toolbar: '#tableBar',  minWidth: 190}
            ];
        // 渲染表格
        var insTb = table.render({
            elem: '#TABLE',
            cellMinWidth: 100,
            url: 'classs/list',
            page: true,
            cols: [ cols ],
            done: function (res, curr, count) {
                hideButton(layui.jquery);
            }
        });

        //居中
        cols.forEach( i => i.align="center");
        // 查询条件
        var reloadTable = w => insTb.reload({where: w || {},page:1});
        // 查询
        form.on('submit(btnSearch)',d =>{reloadTable(d.field);return false;});
        form.on('submit(btnReset)',d =>location.reload);
        // 添加
        form.on('submit(btnAdd)', d => {showEditModel({flag:"add"});return false;});
        // 删除课程
        $("body").on("click","#selectCourseList .js-del-course", e => {
            $(e.target).closest(".js-item").remove();
            resetC();
        });
        // 添加课程
        var addC = v => {
            $("#selectCourseList").append(jsItem.innerHTML);
            v&&$("#selectCourseList select:last").val(v);
            resetC();
        }
        // 获取课程数组
        var getC = x => {
            var c = [];
            $("#selectCourseList select").each((k,v)=>{if(v.value){c.push(v.value)}});
            return c;
        }
        // 选择课程 禁止重复
        var resetC = x => {
            let c = getC();
            $("#selectCourseList option").removeAttr("disabled");
            $("#selectCourseList option").each((k,v)=>{
                if(v.value && !v.selected && c.includes(v.value)) v.disabled = true;
            });
            form.render("select");
        }

        // 统一POST请求封装
        function doPost(url,data,args){
            top.layer.load(2);
            $.post(url, data , function (res){
                top.layer.closeAll('loading');
                let isOk = [0,200].includes(res.code);
                if(res.msg)top.layer.msg(res.msg, {icon: isOk ? 1 :2});
                if(isOk){
                    insTb.reload();//刷列表
                    layer.closeAll('loading');
                    if(typeof args == "function")args(res);//回调
                }
            }, 'json');
        }
        // 工具条点击事件
        table.on('tool(TABLE)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            data.flag = layEvent;
            if(layEvent === 'edit') showEditModel(data); // 修改
            if(layEvent === 'courseStatus') courseStatus(data); // 课程状态
            if(layEvent === 'delClass'){
                if(data.countStudents) return top.layer.msg("班级内有"+data.countStudents+"个学员，移除学员后才可删除班级。", {icon: 2});
                top.layer.confirm("确定要删除吗?<br>此操作不可还原!",r => doPost("classs/delete",{classId:data.id}));
            }
        });
        // 选择机构 级联 校区
        var selectOrg = d => {
            $('#schoolId').html(new Option("请选择", ""));
            schoolList.filter(i=> !d || d == i.organizationId).forEach(i=>$('#schoolId').append(new Option(i.schoolName,i.id)));
            selectSysUser(d);
        };
        var selectSysUser = (o,s) => {
            console.log(1);
            $('#sysUserId').html(new Option("请选择", ""));
            sysUserList.filter( i => !o&&!s || i.id == 1 || o && o == i.organizationId  || s && s == i.schoolId ).forEach(i=>$('#sysUserId').append(new Option(i.nickName,i.id)));
            form.render("select");            
        };

        var selectTeacherUserId = (o,s) => {
            $('#teacherUserId').html(new Option("请选择", ""));
            teacherList.forEach(i=>$('#teacherUserId').append(new Option(i.childName,i.userId)));
            form.render("select");
        };
        // 显示表单弹窗
        function showEditModel(data) {
            let isAdd = !data.id;
            layer.open({
                type: 1,
                title: isAdd ? "添加" : "修改",
                skin: "layui-layer-rim",
                area: ["450px","400px"],
                content: model.innerHTML,
                success:(layero, dIndex)=>{
                    console.log(data);
                    selectOrg(data.toOrganizationId||"");
                    selectTeacherUserId();
                    selectSysUser();
                    
                    // 初始多选课程val
                    data.distributionCourse = data.distributionCourse || "";
                    data.distributionCourse.split(",").forEach((v,k)=>addC(v));

                    form.val("modelForm", data);
                    //添加课程
                    $("#addCourse").click(x=>addC());
                    //联动,机构，校区，班级负责人
                    form.on('select(toOrganizationId)', d=>selectOrg(d.value));
                    form.on('select(schoolId)', d=>selectSysUser(null,));
                    // 选择课程 禁止重复
                    form.on('select(courseId)', d => resetC());
                    resetC();

                    form.on("submit(modelFormSubmit)", d => {
                        d = d.field;
                        var c = [];
                        //$("#selectCourseList select").each((k,v)=>{if(v.value){c.push(v.value)}});
                        d.distributionCourse = "";
                        doPost("classs/crudClass", d, res => layer.close(dIndex) );
                        return false;
                    });

                }
            });
        }


        // 显示分配课程表单弹窗
        function showAddCourseModel(data) {
            //var d=data;
            console.log(data);
            layer.open({
                type: 1,
                title: '课程分配',
                skin: "layui-layer-rim",
                area: ["450px","400px"],
                content: $('#addCourseModel').html(),
                success:(layero, dIndex)=>{
                    //console.log(data);

                    // 初始多选课程val
                    data.distributionCourse = data.distributionCourse || "";
                    data.distributionCourse.split(",").forEach((v,k)=>addC(v));
                    form.val("addCourseModelForm", data);

                    //添加课程
                    $("#addCourse").click(x=>addC());
                    // 选择课程 禁止重复
                    form.on('select(courseId)', d => resetC());
                    resetC();

                    form.on("submit(addCourseModelFormSubmit)", d => {
                        d = d.field;
                        var c = [];
                        $("#selectCourseList select").each((k,v)=>{if(v.value){c.push(v.value)}});
                        d.distributionCourse = getC().join();
                        doPost("classs/crudClass", d,
                        function(res){
                            //console.log(data);
                            //layer.close(dIndex);
                            layer.closeAll();
                            //courseStatus(data);
                        });
                        return false;
                    });

                }
            });
        }

        //选择机构后筛选所负责的校区
        form.on('select(organization)', function (data) {
            changeSchool();
        });

        function changeSchool() {
            $("#toschoolId").empty();
            form.render("select");//重新渲染 固定写法
            var organizationId=$("#toOrganizationId").val();
            console.log(organizationId);
            if(organizationId!=null && organizationId!=""){
                $.ajax({
                    url: '/admin/school/getListByOrganizationId?organizationId='+ organizationId,
                    dataType: 'json',
                    type: 'get',
                    success: function (data) {
                        $('#toschoolId').append(new Option("全部", ""));// 下拉菜单里添加元素
                        $.each(data, function (index, item) {
                            $('#toschoolId').append(new Option(item.schoolName, item.id));// 下拉菜单里添加元素
                        });
                        form.render("select");//重新渲染 固定写法
                    }
                });
            }
        }

        //按钮切换, d.源数据 text.按钮显示文字 url.切换后的请求地址 idk.数据主键id vk.切换字段
        // 修正: 原型图要求仅显示按钮 不让点击.  所以加个 disabled 状态.
        var switchBtn = (d,text,url,idk,vk) => '<input type="checkbox" lay-skin="switch" lay-text="' +text+'" ' +(d.auditStatus != 3?" disabled " : "  ")+ (d[vk]?" checked ":"  ")
            +' value="1" data-idk="'+idk+'" data-idv="'+d[idk]+'" data-vk="'+vk+'" data-url="'+url+'" lay-filter="switchBtn">';
        //按钮切换: 发送请求
        form.on("switch(switchBtn)",function(obj){
            let d = $(obj.elem).data();
            d[d.idk] = d.idv;
            d[d.vk] = obj.elem.checked?1:0;
            $.post(d.url,d);
        });

        // BUG
        setInterval(x=>$(".layui-checkbox-disbaled").removeClass("layui-checkbox-disbaled layui-disabled").css("cursor","not-allowed"),10);
        // 课程状态列表
        function courseStatus(data){
            console.log(data);
            top.layer.load(2);
            $.post("classs/getClassCourseList",data,res=>{
                top.layer.closeAll('loading');
                layer.open({
                    type: 1,
                    title: data.className + "课程",
                    skin: "layui-layer-rim",
                    maxmin:true,
                    area: ["800px","500px"],
                    content: '<div><table class="layui-table" id="courseTable" lay-filter="courseTable"></table></div>',
                    success:(layero, dIndex)=>{
                        let cols = [
                            {checkbox:true,width:50},
                            {title:"单元",field:"unitName" },
                            {title:"课程",field:"courseId" ,templet:d=>courseList.filter(i=>i.id==d.courseId).map(i=>i.courseName).join() },
                            {title:"审核",field:"auditStatus" ,templet:d=>"未申请 审核中 审核失败 审核成功".split(" ")[d.auditStatus] || "未知"},
                            {title:"审核意见",field:"remark" },
                            {title:"状态",field:"status" ,templet:d=>switchBtn(d,"解锁|锁定","classs/editClassCourseStatus","id","status")},
                            {title:"操作",toolbar: '#tableBarCourse'}
                        ]
                        cols.forEach( i => i.align="center");
                        table.render({elem:"#courseTable",data:res,cols:[cols],page: false,limit:999999999,toolbar:"#toolbar1"});
                        table.on('tool(courseTable)', function (obj) {
                            var d = obj.data;
                            var layEvent = obj.event;
                            d.flag = layEvent;
                            if(layEvent === 'unlockStatus')top.layer.confirm("确定要申请解锁吗?",r => doPost("classs/courseStatus",{ids:d.id,auditStatus:1},x=>location.reload()));
                            if(layEvent === 'auditStatus')auditStatus(d.id);
                        });
                        table.on("toolbar(courseTable)",function(obj){
                            var flag = obj.event;
                            if(flag == "auditStatusBatch" ) {
                                var d = table.checkStatus(obj.config.id);
                                if(!d.data.length)return top.layer.msg("请选择", {icon: 2});
                                auditStatus(d.data.map(i=>i.id).join());//批量审核
                            }
                            if(flag == "addCourse2"){
                                showAddCourseModel(data);
                            }
                        });
                    }
                });
            });
        }
        var setAuditStatus = d => doPost("classs/courseAuditStatus" ,d ,x=>location.reload());
        function auditStatus(ids){
            var a = layer.prompt({
                formType:2
                ,title:"审核"
                ,btn:["通过","不通过","取消"]
                ,btnAlign:"c"
                ,yes : (x,y) => setAuditStatus({ids,status:1,auditStatus:3,remark:y.find(".layui-layer-input").val()})
                ,btn2: (x,y) => setAuditStatus({ids,status:0,auditStatus:2,remark:y.find(".layui-layer-input").val()})
            });
        }
    });
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="model">
    <form id="modelForm" lay-filter="modelForm" class="layui-form model-form">
        <input type="hidden" name="id" />
        <input type="hidden" name="flag" />
        <div style="height:370px;overflow:hidden auto;">

            <div class="layui-form-item">
                <label class="layui-form-label">班级名称</label>
                <div class="layui-input-block">
                    <input name="className" placeholder="请输入" lay-verify="required" lay-verType="tips" type="text" autocomplete="off" class="layui-input"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">所属机构</label>
                <div class="layui-input-block">
                    <select name="toOrganizationId" lay-filter="toOrganizationId" xm-select="toOrganizationId" lay-verType="tips" lay-verify="required">
                        <option value="">请选择</option>
                        <% for(organization in organizationList) { %>
                        <option value="${organization.id}">${organization.organizationName}</option>
                        <% } %>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">所属校区</label>
                <div class="layui-input-block">
                    <select name="schoolId" id="schoolId"  lay-filter="schoolId" xm-select="schoolId" lay-verType="tips" lay-verify="required"></select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">班级负责人</label>
                <div class="layui-input-block">
                    <select name="sysUserId" id="sysUserId"></select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">分配教师:</label>
                <div class="layui-input-block">
                    <select name="teacherUserId" id="teacherUserId"></select>
                </div>
            </div>
            <!-- 课程 -->
            <!--<div id="selectCourseList"></div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block">
                    <span id="addCourse" class="layui-btn">增加课程</span>
                </div>
            </div>-->

        </div>
        <div class="layui-form-item text-center js-bottom-btn">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closePageDialog">取消</button>
            <button class="layui-btn" lay-filter="modelFormSubmit" lay-submit>保存</button>
        </div>
    </form>
    <style>
        /* 隐藏第一个删除 */
        #selectCourseList>.js-item:first-child .js-del-course{display:none}
        /* 显示第一个标题 */
        #selectCourseList>.js-item:first-child .js-title::after{content:"分配课程"}
        /* 单元名称/序号 */
        #selectCourseList{counter-reset:units;}
        #selectCourseList .js-units::before{counter-increment:units;content:"unit" counter(units)}

        #modelForm .layui-anim.layui-anim-upbit{max-height:180px;}
    </style>
</script>

<!-- 课程状态添加课程 表单弹窗 -->
<script type="text/html" id="addCourseModel">
    <form id="addCourseModelForm" lay-filter="addCourseModelForm" class="layui-form model-form">
        <input type="hidden" name="id" />
        <input type="hidden" name="flag" />
        <div style="height:370px;overflow:hidden auto;">

            <!-- 课程 -->
            <div id="selectCourseList"></div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block">
                    <span id="addCourse" class="layui-btn">增加课程</span>
                </div>
            </div>

        </div>
        <div class="layui-form-item text-center js-bottom-btn">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closePageDialog">取消</button>
            <button class="layui-btn" lay-filter="addCourseModelFormSubmit" lay-submit>保存</button>
        </div>
    </form>
    <style>
        /* 隐藏第一个删除 */
        #selectCourseList>.js-item:first-child .js-del-course{display:none}
        /* 显示第一个标题 */
        #selectCourseList>.js-item:first-child .js-title::after{content:"分配课程"}
        /* 单元名称/序号 */
        #selectCourseList{counter-reset:units;}
        #selectCourseList .js-units::before{counter-increment:units;content:"unit" counter(units)}

        #addCourseModelForm .layui-anim.layui-anim-upbit{max-height:180px;}
    </style>
</script>



<!-- 课程选择模板 -->
<script type="text/html" id="jsItem">
    <div class="layui-form-item js-item">
        <label class="layui-form-label js-title"></label>
        <div class="layui-form-mid layui-word-aux js-units"></div>
        <div class="layui-input-inline">
            <select name="courseId" lay-filter="courseId" xm-select="courseId" lay-verType="tips" lay-verify="required">
                <option value="">请选择课程</option>
                <% for(course in courseList) { %>
                    <option value="${course.id}">${course.courseName}</option>
                <% } %>
            </select>
        </div>
        <div class="js-del">
            <span class="layui-btn layui-btn-danger layui-btn-sm js-del-course">删除</span>
        </div>
    </div>
</script>

<!-- 班级表格操作列 -->
<script type="text/html" id="tableBar">
    <a data-button="class:update" class="layui-btn layui-btn-normal layui-btn-xs role_menu" lay-event="edit">编辑</a>
    <!-- 主校区管理员、机构管理员、子校区管理员均可操作。 -->
    {{# if( maxRoleSerialNumber < 4 ) { }}
        <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="courseStatus">课程状态</a>
    {{#  } }}
    <a data-button="class:delete" class="layui-btn layui-btn-danger layui-btn-xs role_menu" lay-event="delClass">删除</a>
</script>
<!-- 课程表格操作列 -->
<script type="text/html" id="tableBarCourse">
    <!-- 机构管理员、子校区去管理员 可操作申请解锁 -->
    {{# if( d.status == 0 && [0,2].includes(d.auditStatus) && (maxRoleSerialNumber == 2 || maxRoleSerialNumber == 3) ) { }}
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="unlockStatus">申请解锁</a>
    {{#  } }}
    <!-- 主校区管理员 可操作 审核 , 审核之后 可以重复审核 -->
    {{# if( maxRoleSerialNumber == 1 && d.auditStatus != 0  ) { }}
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="auditStatus">审核</a>
    {{#  } }}
</script>
<script type="text/html" id="toolbar1">
    <div>
    {{# if( maxRoleSerialNumber == 1) { }}
        <button lay-event="auditStatusBatch" class="layui-btn icon-btn layui-btn-normal">审核</button>
    {{#  } }}
        <button lay-event="addCourse2" class="layui-btn icon-btn layui-btn-normal">课程分配</button>
    </div>
</script>

</body>
</html>